/*******************************************************************************
  Main Source File

  Company:
    Microchip Technology Inc.

  File Name:
    main.c

  Summary:
    This file contains the "main" function for bootloader project.

  Description:
    This file contains the "main" function for bootloader project.  The
    "main" function calls the "SYS_Initialize" function to initialize
    all modules in the system.
    It calls "bootloader_start" once system is initialized.
 *******************************************************************************/

// DOM-IGNORE-BEGIN
/*******************************************************************************
* Copyright (C) 2019 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
* INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
* WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
* BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
* FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
* ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
 *******************************************************************************/
// DOM-IGNORE-END

// *****************************************************************************
// *****************************************************************************
// Section: Included Files
// *****************************************************************************
// *****************************************************************************

#include <stddef.h>                     // Defines NULL
#include <stdbool.h>                    // Defines true
#include <stdlib.h>                     // Defines EXIT_FAILURE
#include "definitions.h"                // SYS function prototypes
#include "../src/SPI_FrameWork.h"
#include "../src/Framework.h"
#include "../src/PanelComm.h"
#include "../src/IoComm.h"
#include "../src/IoComm_CommandHandler.h"
#include "../src/CommandHandler.h"
#include "../src/Uart3.h"
#include "../src/Uart4.h"
#include "../src/Uart5.h"
#include "Uart1.h"
#include "../src/Debug.h"

#define BTL_TRIGGER_PATTERN (0x5048434DUL)

static uint32_t *ramStart = (uint32_t *)BTL_TRIGGER_RAM_START;
bool bootloader_Trigger(void)
{
    uint32_t i;

    // Cheap delay. This should give at leat 1 ms delay.
    for (i = 0; i < 2000; i++)
    {
        asm("nop");
    }

    /* Check for Bootloader Trigger Pattern in first 16 Bytes of RAM to enter Bootloader.*/
    if (BTL_TRIGGER_PATTERN == ramStart[0] && BTL_TRIGGER_PATTERN == ramStart[1] &&
        BTL_TRIGGER_PATTERN == ramStart[2] && BTL_TRIGGER_PATTERN == ramStart[3])
    {
        ramStart[0] = 0;
        return true;
    }

    /* Check for Switch press to enter Bootloader */
//    if (SWITCH_Get() == 0)
//    {
//        return true;
//    }

    return false;
}

// *****************************************************************************
// *****************************************************************************
// Section: Main Entry Point
// *****************************************************************************
// *****************************************************************************

#define  BOOT_APP_MERGE_EN   1  // 1 boot and app merge enable, 0 disable
#if(BOOT_APP_MERGE_EN)
const uint32_t __attribute__((address(APP_Flay_FlashAddr),space(prog),keep)) APP_Flay[2] =
{
    0x00AA,0x0000
};
#endif

BOOL bAppStatus;
BOOL b1ms;
BOOL CheckAppProgram(void);
void Timer1_Polled(void);
uint8_t SPI2_Trans_Tx[12];
int mode = 1;
volatile uint16_t * wdtclrkey = ( (volatile uint16_t *)&WDTCON ) + 1;
int main ( void )
{
    /* Initialize all modules */
    SYS_Initialize ( NULL );
    PanelComm_Init();
    IoComm_Init();
    Uart1Comm_Init();
    bAppStatus = 1;
//   SPI4_CallbackRegister(SPIEventHandler, (uintptr_t) 0); 
    SPI2_Trans_Tx[0] = 0xAA;
    SPI2_Trans_Tx[1] = 0x00;
    SPI2_Trans_Tx[2] = 0xE2;
    SPI2_Trans_Tx[3] = 0x07;
    SPI2_Trans_Tx[4] = 0x00;
    SPI2_Trans_Tx[5] = 0x05;
    SPI2_Trans_Tx[6] = 0x00;
    SPI2_Trans_Tx[7] = 0x01;
    SPI2_Trans_Tx[8] = 0xBB;
    SPI2_Trans_Tx[9] = 0xFF;
    SPI2_Trans_Tx[10] = 0xFF;
    SPI2_Trans_Tx[11] = 0xFF;
    
    while (true)
    {
        bootloader_UART_Tasks();   
        PanelComm_RxTx();
        IoComm_RxTx();
        ExtendAxisComm_RxTx();
        
        PanelComm_BuildRecPack();
        IoComm_BuildRecPack();
        ExtendAxis_BuildRecPack();
        
        CommandHandler_Execute();
        IoComm_CommandHandler_Execute();
        ExtendAxis_CommandHandler_Execute();
        
        UART_Response_Func();
        RotateAxis_Response_Func();
        
        Timer1_Polled();
        *wdtclrkey = 0x5743; 
        Nop(); Nop();
    }
    /* Execution should not come here during normal operation */
    return ( EXIT_FAILURE );
}
void Timer1_Polled(void)
{
    if(IFS0bits.T1IF)
    {
        IFS0bits.T1IF = 0;
         b1ms = 1;
    }
}
/********************************************************************
* Function: 	CheckAppProgram()
* Precondition: 
* Input: 		None.
* Output:		
* Side Effects:
* Overview: 	CheckAppProgram
* Note:		 	None.
********************************************************************/
BOOL CheckAppProgram(void)    /* Return 1: yes, return 0: no */
{
    uint32_t   app_fly[1] = {0};
    uint8_t    soft_reset;

    uint32_t   data[1] = {0};
    bAppStatus = 0;   /* The global variable is assigned the value 0 */
    soft_reset = RCONbits.SWR;

    if(soft_reset)             /* If software reset has been performed */
    {
        RCONbits.SWR = 0;      /* Flag reset */
    }

    if(NVM_Read((uint32_t *)app_fly,1,APP_Flay_FlashAddr))
    {
        if(app_fly[0] == DEF_APP_FLAY)       /* If is equal to 0xAA */
        {
            if(soft_reset)                /* A software reset has been performed */
            {
                bAppStatus = 0;        /* The APP exists but is not used */
                return FALSE;          /* Cannot run APP (reset, need to upgrade) */
            }
            else              /* Read the user's APP start address without performing software reset (just completed upgrade) */
            {
                // data  = FLASH_ReadWord24(USER_APP_START_ADDRESS);  
                if(NVM_Read((uint32_t *)data,1,USER_APP_START_ADDRESS))   /* Read the user's APP start address */
                {
                    if(data[0] == 0xFFFFFF)
                    {
                        bAppStatus = 1;  /* APP does not exist */
                        return FALSE;    /* No APP (no reset) */
                    }
                    else
                    {
                        return TRUE;/* state=1; */      /* There is APP (neither reset nor 0xffffff) */
                    }
                }
            }       
        }
    }
    bAppStatus = 1;   /* If not equal to regardless of the reset flag bit, position 1 will be marked */
    return FALSE;    /* no APP */
}
/*******************************************************************************
 End of File
*/
